import type {
  RouteLocationNormalizedLoadedGeneric,
  RouteRecordName
} from "vue-router"

export const useTagsViewStore = defineStore("tagsView", () => {
  const visitedViews = ref<RouteLocationNormalizedLoadedGeneric[]>([])

  //区分那些需要缓存
  const cachedViews = ref<RouteRecordName[]>([])

  const addView = (view: RouteLocationNormalizedLoadedGeneric) => {
    // 当前试图是否已存在
    const exits = visitedViews.value.some((v) => v.path === view.path)
    addCacheView(view)
    if (exits) return

    const newView = {
      ...view,
      title: view.meta.title
    }
    visitedViews.value.push(newView)
  }

  const deleteView = (view: RouteLocationNormalizedLoadedGeneric) => {
    const index = visitedViews.value.findIndex((v) => v.path === view.path)
    if (index > -1) {
      visitedViews.value.splice(index, 1)
    }
    deleteCacheView(view)
  }

  // 添加缓存
  const addCacheView = (view: RouteLocationNormalizedLoadedGeneric) => {
    if (cachedViews.value.includes(view.name)) return

    if (!view.meta.noCache) {
      cachedViews.value.push(view.name)
    }
  }

  // 删除缓存
  const deleteCacheView = (view: RouteLocationNormalizedLoadedGeneric) => {
    const index = cachedViews.value.indexOf(view.name)
    if (index > -1) {
      cachedViews.value.splice(index, 1)
    }
  }

  const delAllView = () => {
    visitedViews.value = visitedViews.value.filter((view) => view.meta.affix)
    cachedViews.value = []
  }

  const deleteOtherView = (view: RouteLocationNormalizedLoadedGeneric) => {
    visitedViews.value = visitedViews.value.filter(
      (v) => v.meta.affix || v.path === view.path
    )
    cachedViews.value = cachedViews.value.filter((name) => name === view.name)
  }
  return {
    visitedViews,
    addView,
    deleteView,
    cachedViews,
    delAllView,
    deleteOtherView,
    deleteCacheView
  }
})
